import React from 'react';
import { Modal, Input, message, Form, Button } from 'antd';
import { postUserTypeAdd, postUserTypeEdit, getUserTypeInfo } from '@/services/basiccapacity';

class Revise extends React.Component {
  state = {
    id: '',
    visible: false,
  };

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  init = id => {
    this.setState({ visible: true, id: id ? id : null }, async () => {
      if (id) {
        let res = await getUserTypeInfo({ id });
        if (res) {
          console.log(res);
          this.props.form.setFieldsValue({
            typeName: res.typeName,
            typeCode: res.typeCode,
          });
        }
      }
    });
  };

  close = () => {
    this.setState({ visible: false });
  };

  submit = () => {
    const { id } = this.state;
    let _this = this;
    this.props.form.validateFields(async (err, values) => {
      if (!err) {
        let res = { data: false, msg: '操作失败' };
        if (!id) {
          let obj = { ...values, typeCode: values.typeCode.trim() };
          res = await postUserTypeAdd(obj);
        } else {
          let obj = { ...values, id, typeCode: values.typeCode.trim() };
          res = await postUserTypeEdit(obj);
        }
        console.log(res);
        if (res.msg == '操作成功') {
          message.info(res.msg);
          _this.close();
          _this.props.getList();
        }
      }
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { visible } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 6 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 18 },
        sm: { span: 18 },
      },
    };

    return (
      <Modal
        title="添加/编辑用户类型"
        visible={visible}
        onCancel={this.close}
        destroyOnClose
        footer={[
          <Button onClick={this.close}>取消</Button>,
          <Button type="primary" onClick={this.submit}>
            确定
          </Button>,
        ]}
      >
        <Form {...formItemLayout}>
          <Form.Item label="用户类型名称">
            {getFieldDecorator('typeName')(<Input placeholder="请输入" />)}
          </Form.Item>
          <Form.Item label="用户类型字段值">
            {getFieldDecorator('typeCode')(<Input placeholder="请输入" />)}
            <p style={{ color: '#bfbfbf', fontSize: '13px', lineHeight: '16px' }}>
              该类型用户发起会话时，系统实际传的字段值
            </p>
          </Form.Item>
        </Form>
      </Modal>
    );
  }
}

export default Form.create()(Revise);
